package com.huluobo.a2203parkdemo.news

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.huluobo.a2203parkdemo.adapter.NewsAdapter
import com.huluobo.a2203parkdemo.databinding.ActivityNewsBinding
import com.huluobo.base.bean.NewsBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class NewsActivity : BaseActivity<ActivityNewsBinding, NewsViewModel>() {
    private lateinit var newsAdapter: NewsAdapter

    override fun initData() {
        val map = mutableMapOf<String, Int>()
        map[Const.PARAM_PAGE] = 0
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        viewModel.getNews(body)

        viewModel.getNewsSuccess.observe(this) {
            val newsList = Gson().fromJson(it, NewsBean::class.java)
            newsAdapter.data.addAll(newsList)
            newsAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        binding.newRv.layoutManager = LinearLayoutManager(this)
        newsAdapter = NewsAdapter()
        binding.newRv.adapter = newsAdapter

        binding.newsHeader.headerBack.setOnClickListener {
            finish()
        }

        binding.newsHeader.headerTitle.text = "新闻"

        binding.newsHeader.headerAdd.visibility = View.VISIBLE
        binding.newsHeader.headerAdd.setOnClickListener {
            val intent = Intent(this, AddNewsActivity::class.java)
            startActivity(intent)
            finish()
        }
    }
}